package com.zhentao.service.impl;

import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.zhentao.exception.ZhentaoException;
import com.zhentao.mapper.SysUserRoleMapper;
import com.zhentao.minio.service.FileStorageService;
import com.zhentao.model.dto.system.AssginRoleDto;
import com.zhentao.model.dto.system.LoginDto;
import com.zhentao.model.dto.system.SysUserDto;
import com.zhentao.model.entity.system.SysUser;
import com.zhentao.model.vo.common.ResultCodeEnum;
import com.zhentao.model.vo.system.LoginVo;
import com.zhentao.service.SysUserService;
import com.zhentao.mapper.SysUserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.DigestUtils;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.List;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

/**
* @author 懒阳阳
* @description 针对表【sys_user(用户表)】的数据库操作Service实现
* @createDate 2025-02-08 14:45:04
*/
@Service
public class SysUserServiceImpl implements SysUserService {

    @Autowired
    private SysUserMapper sysUserMapper;

    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    @Autowired
    private FileStorageService fileStorageService;

    @Autowired
    private SysUserRoleMapper sysUserRoleMapper;

    @Override
    public LoginVo login(LoginDto loginDto) {

        //校验验证码是否正确
        String captcha = loginDto.getCaptcha();   //用户输入的验证码
        String codeKey = loginDto.getCodeKey();   //redis里面保存的验证码的key

        // 从redis中获取验证码图片
        String redisCode = redisTemplate.opsForValue().get("user:login:validatecode:" + codeKey);
        if(StrUtil.isEmpty(redisCode) || !StrUtil.equalsIgnoreCase(redisCode, captcha)){
            throw new ZhentaoException(ResultCodeEnum.VALIDATECODE_ERROR);
        }

        //验证通过删除redis中的验证码
        redisTemplate.delete("user:login:validatecode:" + codeKey);

    //.............
        //根据用户名查询用户
        SysUser sysUser = sysUserMapper.selectByUserName(loginDto.getUserName());
        if(sysUser == null){
            throw new ZhentaoException(ResultCodeEnum.LOGIN_ERROR);
        }

        //校验密码是否正确
        String inputPassword = loginDto.getPassword();
        String md5InputPassword = DigestUtils.md5DigestAsHex(inputPassword.getBytes());
        if(!md5InputPassword.equals(sysUser.getPassword())){
            throw new ZhentaoException(ResultCodeEnum.LOGIN_ERROR);
        }

        //生成令牌,将数据保存到redis中
        String token = UUID.randomUUID().toString().replace("-", "");
        redisTemplate.opsForValue().set("user:login:" + token, JSON.toJSONString(sysUser), 30, TimeUnit.MINUTES);

        //建造响应结果对象
        LoginVo loginVo = new LoginVo();
        loginVo.setToken(token);
        loginVo.setRefresh_token("");

        //返回结果
        return loginVo;
    }

    //退出登录
    @Override
    public void logout(String token) {
        redisTemplate.delete("user:login:" + token);
    }

    @Override
    public PageInfo<SysUser> findByPage(SysUserDto sysUserDto, Integer pageNum, Integer pageSize) {
        PageHelper.startPage(pageNum, pageSize);
        List<SysUser> sysUsers = sysUserMapper.findByPage(sysUserDto);
        PageInfo<SysUser> pageInfo = new PageInfo<>(sysUsers);
        return pageInfo;
    }

    //添加用户
    @Override
    public void saveSysUser(SysUser sysUser) {

        //根据输入的用户名查询用户 判断用户是否存在
        SysUser dbSysUser = sysUserMapper.findByUserName(sysUser.getUsername());
        if(dbSysUser != null){
            throw new ZhentaoException(ResultCodeEnum.USER_NAME_IS_EXISTS);
        }

        //对输入的密码进行加密
        String password = sysUser.getPassword();
        String digestPassword = DigestUtils.md5DigestAsHex(password.getBytes());
        sysUser.setPassword(digestPassword);
        sysUser.setStatus(0);
        sysUserMapper.saveSysUser(sysUser);

    }

    //修改用户
    @Override
    public void updateSysUser(SysUser sysUser) {
        String s = DigestUtils.md5DigestAsHex(sysUser.getPassword().getBytes());
        sysUser.setPassword(s);
        sysUserMapper.updateSysUser(sysUser);
    }

    //删除用户
    @Override
    public void deleteSysUser(Long userId) {
        sysUserMapper.deleteUserById(userId);
    }

    //为用户分配角色
    @Override
    @Transactional
    public void doAssign(AssginRoleDto assginRoleDto) {
        //删除之前的所有用户所对应的角色数据
        sysUserRoleMapper.deleteByUserId(Long.valueOf(assginRoleDto.getUserId()));

        //分配新的角色数据
        List<Long> roleIdList = assginRoleDto.getRoleIdList();
        roleIdList.forEach(roleId->{
            sysUserRoleMapper.doAssign(Long.valueOf(assginRoleDto.getUserId()), roleId);
        });
    }

    @Override
    public String uploadImages(MultipartFile file) throws IOException {
        if(file==null || file.getSize()<0){
            return "";
        }
        String s = fileStorageService.uploadPicFile(file.getOriginalFilename(), file.getInputStream());
        return s;
    }
}




